<?php

namespace app\ice\controller;
use think\Db;
use think\Loader;
use app\ice\model\Goods;
use app\ice\model\UserAddress;
use app\ice\model\User;
use app\ice\model\LuckDraw;
use think\Exception;
use app\ice\model\Order as OrderModel;
use app\ice\model\OrderGoods;
use app\ice\model\Discount;
use app\ice\model\ScoreLog;
class Activity extends Init
{
    
    protected function _initialize()
    {
        parent::_initialize();
        $this->AreaModel = Loader::model('Area');
        $this->UserAddressModel = Loader::model('UserAddress');
        $this->UserModel = Loader::model('User');
        $this->LuckDrawModel = Loader::model('LuckDraw');
        $this->DiscountModel = Loader::model('Discount');
    }


    public function index(){
        $param = input('post.');
        $result = $this->DiscountModel->getList();
	    return ['data' => $result, 'code' => 200, 'message' => '显示成功', 'status' => true];
    }

    //抽奖
    public function luckDraw(){
        $param = input('post.');
        db::startTrans();
        try {
            $prize_arr = Db::name('Discount')->where(array('grant_status'=>1))->select();
            $arr = array_column($prize_arr, 'v','id');
            $rid = get_rand($arr); //根据概率获取奖项id
            $info = Db::name('Discount')->find($rid);
            $key = array_search($rid, array_column($prize_arr,'id'));
            $info['key'] = $key;
            $score = $this->UserModel->getUserData($param)['score'];
            $delScore = $this->LuckDrawModel->getDetail($param['ruleId'])['score'];
            if($score < $delScore){
                return ['data' => [], 'code' => 400, 'message' => '积分不足', 'status' => false];
            }
            $delScoreRes = db('userInfo')->where('id', $param['uid'])->setDec('score',$delScore);
            $scoreData['score'] = $delScore;
            $scoreData['mark'] = '积分抽奖';
            $scoreData['type'] = 2;
            $scoreData['uid'] = $param['uid'];
            $scoreData['addTime'] = time();
            $scoreData['updateTime'] = time();
            $scoreLog = new ScoreLog();
            $scoreLog->saveLog($scoreData);
            $myScore = $this->UserModel->getUserData($param)['score'];
            $addOrder = false;
            $addGoods = false;
            if($info['status'] == 1 && $info['really'] == 1){
                $goods  = db::name('goods')->field('id,price,goods_name')->where('id',$info['goods_id'])->find();
                $order  = new OrderModel();
                $order->province     = $this->AreaModel->getName($param['provinceId']);
                $order->city     = $this->AreaModel->getName($param['cityId']);
                $order->district     = $this->AreaModel->getName($param['districtId']);
                $order->address    = $param['address'];
                $order->consignee    = $param['linkMan'];
                $order->code    = $param['code'];
                $order->mobile    = $param['mobile'];
                $order->goods_price    = $goods['price'];
                $order->uid    = $param['uid'];
                $order->add_time    = time();
                $order->status    = 1;
                $order->type    = 2;
                $order->order_sn    = time().rand(000000,999999);
                $order->address    = $param['address'];
                $addOrder = $order->save();
                // 获取自增ID
                $OrderGoods  = new OrderGoods;
                $goods['order_id'] = $order->order_id;
                $goods['goods_num'] = 1;
                $goods['goods_id'] = $goods['id'];
                $goods['goods_price'] = $goods['price'];
                $OrderGoods->data($goods);
                $addGoods = $OrderGoods->save();
            }elseif($info['status'] == 1){
                $Log = new ScoreLog();
                $addScoreRes = db('userInfo')->where('id', $param['uid'])->setInc('score',$info['price']);
                $addScoreData['score'] = $info['price'];
                $addScoreData['mark'] = '积分抽奖';
                $addScoreData['type'] = 1;
                $addScoreData['uid'] = $param['uid'];
                $addScoreData['addTime'] = time();
                $addScoreData['updateTime'] = time();
                $Log->saveLog($addScoreData);
                $myScore = $myScore + $info['price'];
            }
            if($info && $prize_arr && $score && $delScore && ( $myScore >= 0) && $delScoreRes){
                $info['myScore'] = $myScore;
                db::commit();
            }else{
                throw new Exception("error");
            }
        } catch (Exception $e) {
            db::rollback();
            return ['data' => [], 'code' => 400, 'message' => $e->getMessage(), 'status' => false];
        }
        if($info['status']){
            return ['data' => $info, 'code' => 200, 'message' => '显示成功', 'status' => true];
        }else{
            return ['data' => $info, 'code' => 200, 'message' => '显示成功', 'status' => false];
        }
    }

    //抽奖
    public function luckDrawRule(){
        $param = input('post.');
        $data = $this->LuckDrawModel->getDetail($param['id']);
        return ['data' => $data, 'code' => 200, 'message' => '显示成功', 'status' => true];
    }

    //抽奖
    public function luckDrawDetail(){
        $param = input('post.');
        $data = db::name('luckDraw')->where('status',1)->order('id desc')->find();
        return ['data' => $data, 'code' => 200, 'message' => '显示成功', 'status' => true];
    }

    public function detail(){
        $param = input('post.');
        $result = $this->UserAddressModel->getAddressDetail($param);
        if($result){
            $result['provinceStr'] = $this->AreaModel->getName($result['provinceId']);
            $result['cityStr'] = $this->AreaModel->getName($result['cityId']);
            $result['areaStr'] = $this->AreaModel->getName($result['districtId']);
            if($result['isDefault']){
                $result['isDefault'] = true;
            }else{
                $result['isDefault'] = false;
            }
        }
        return ['data' => $result, 'code' => 200, 'message' => '显示成功', 'status' => true];
    }

    public function add(){
        $param = input('post.');
        $model = new UserAddress($param);
        $result = $model->allowField(true)->save();
        return ['data' => $result, 'code' => 200, 'message' => '添加成功', 'status' => true];
    }

    public function update(){
        $param = input('post.');
        $model = new UserAddress();
        $result = $model->allowField(true)->save($param, ['address_id' => $param['id']]);
        return ['data' => $result, 'code' => 200, 'message' => '编辑成功', 'status' => true];
    }

    public function getList(){
        $param = input('post.');
        $result = $this->UserAddressModel->getAddressList($param);
        return ['data' => $result, 'code' => 200, 'message' => '显示成功', 'status' => true];
    }

}
